package edu.gyc.hiseckill.error;

import edu.gyc.hiseckill.model.CommonReturnType;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@ControllerAdvice
public class MyExceptionHandler {

    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public Object handlerException(HttpServletRequest request, Exception e) {
        e.printStackTrace();
        Map<String, Object> datamap = new HashMap<>();
        if (e instanceof BusinessException) {
            BusinessException businessException = (BusinessException)e;

            datamap.put("errCode", businessException.getErrorCode());
            datamap.put("errMsg", businessException.getErrorMessage());
        }else {
            datamap.put("errCode", BusinessErrorEnum.UNKNOWN_ERROR.getErrorCode());
            datamap.put("errMsg", e.getLocalizedMessage());
        }
        CommonReturnType commonReturnType=CommonReturnType.create(e,"fail");
        commonReturnType.setData(datamap);
        return commonReturnType;
    }

}
